
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


public class ChatRobot {
    public static void main(String[] args) {
        getQustionAndAnswer();
    }

    /**
     * 调用readFileAnswer方法，获取问题和答案
     */
    public static void getQustionAndAnswer() {
        System.out.println("——————智能聊天窗口——————");
        Map<String, String> answerMap = readFileAnswer();
        //获取用户输入数据
        Scanner scaner = new Scanner(System.in);
        while (true) {
            System.out.print("请输入您的问题:");
            String question = scaner.nextLine();
            if (question == null || "".equals(question)) {
                continue;
            }
            String answer=null;
            for (Map.Entry<String, String> entry:answerMap.entrySet() ){
                if (question.contains(entry.getKey())){
                    answer=entry.getValue();
                    break;
                }
            }
            if (answer!=null && !"".equals(answer)){
                System.out.println("你的问题答案是："+answer);
            }
            else {
                System.out.println("你的问题好深奥哦，换个问题吧。");
            }
        }

    }

    /**
     * 读取文件内容到MAP对象，Map对象存储
     */
    public static Map<String, String> readFileAnswer() {
        Map<String, String> answerMap = new HashMap<>(1024);
        BufferedReader bufferedReader = null;
        try {
            File fileAdress = new File(".\\src\\answer.txt");
            bufferedReader = new BufferedReader(new FileReader(fileAdress));
            String lineText = null;
            do {
                lineText = bufferedReader.readLine();
                System.out.println("读到一行数据：" + lineText);
                if (lineText != null) {
                    String[] stringArray = lineText.split("，");
                    if (stringArray.length >= 2) {
                        answerMap.put(stringArray[0], stringArray[1]);
                    }
                }
            } while (lineText != null);
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return answerMap;
    }
}
